/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int ans;

    public int diameterOfBinaryTree(TreeNode root) {
        ans = 1;
        getRadius(root);
        return ans - 1;
    }

    /**
     * 计算此节点为根的子树深度
     * @param node
     * @return
     */
    public int getRadius(TreeNode node) {
        if (node == null)
            return 0;
        
        int left = getRadius(node.left);
        int right = getRadius(node.right);
        ans = Math.max(diameter, left+right); // 两个子树深度和的最大值，减一即为直径（当前节点算了两次）
        return Math.max(left, right)+1;
    }
}